import sqlite3
from PySide6.QtWidgets import QApplication
from PySide6.QtGui import QPalette, QColor
from PySide6.QtCore import Qt


class ThemeManager:
    def __init__(self, db_path="work_monitor.db"):
        self.db_path = db_path
        self.themes = {
            "default_blue": {
                "name": "默认蓝调",
                "description": "经典商务蓝，专业稳重",
                "primary": "#2563eb",
                "secondary": "#1e40af",
                "accent": "#3b82f6",
                "background": "#f8fafc",
                "card_bg": "rgba(248, 250, 252, 0.95)",
                "text": "#1e293b",
                "text_secondary": "#64748b",
                "border": "rgba(148, 163, 184, 0.3)",
                "success": "#10b981",
                "warning": "#f59e0b",
                "error": "#ef4444",
                "gradient_start": "#3b82f6",
                "gradient_end": "#1d4ed8"
            },
            "midnight_purple": {
                "name": "午夜紫",
                "description": "神秘优雅，夜间护眼",
                "primary": "#7c3aed",
                "secondary": "#5b21b6",
                "accent": "#8b5cf6",
                "background": "#0f0f23",
                "card_bg": "rgba(30, 27, 75, 0.95)",
                "text": "#e2e8f0",
                "text_secondary": "#94a3b8",
                "border": "rgba(139, 92, 246, 0.3)",
                "success": "#34d399",
                "warning": "#fbbf24",
                "error": "#f87171",
                "gradient_start": "#7c3aed",
                "gradient_end": "#3730a3"
            },
            "emerald_green": {
                "name": "翡翠绿",
                "description": "自然清新，护眼舒适",
                "primary": "#059669",
                "secondary": "#047857",
                "accent": "#10b981",
                "background": "#f0fdf4",
                "card_bg": "rgba(240, 253, 244, 0.95)",
                "text": "#064e3b",
                "text_secondary": "#374151",
                "border": "rgba(16, 185, 129, 0.3)",
                "success": "#22c55e",
                "warning": "#eab308",
                "error": "#dc2626",
                "gradient_start": "#10b981",
                "gradient_end": "#047857"
            },
            "rose_gold": {
                "name": "玫瑰金",
                "description": "温柔浪漫，时尚典雅",
                "primary": "#e11d48",
                "secondary": "#be185d",
                "accent": "#f43f5e",
                "background": "#fdf2f8",
                "card_bg": "rgba(253, 242, 248, 0.95)",
                "text": "#881337",
                "text_secondary": "#9f1239",
                "border": "rgba(244, 63, 94, 0.3)",
                "success": "#16a34a",
                "warning": "#ca8a04",
                "error": "#dc2626",
                "gradient_start": "#f43f5e",
                "gradient_end": "#be185d"
            },
            "amber_orange": {
                "name": "琥珀橙",
                "description": "活力温暖，激发创意",
                "primary": "#ea580c",
                "secondary": "#c2410c",
                "accent": "#f97316",
                "background": "#fffbeb",
                "card_bg": "rgba(255, 251, 235, 0.95)",
                "text": "#9a3412",
                "text_secondary": "#a16207",
                "border": "rgba(249, 115, 22, 0.3)",
                "success": "#15803d",
                "warning": "#d97706",
                "error": "#dc2626",
                "gradient_start": "#f97316",
                "gradient_end": "#c2410c"
            },
            "deep_sea": {
                "name": "深海蓝",
                "description": "深邃宁静，专注工作",
                "primary": "#0891b2",
                "secondary": "#0e7490",
                "accent": "#06b6d4",
                "background": "#ecfeff",
                "card_bg": "rgba(236, 254, 255, 0.95)",
                "text": "#164e63",
                "text_secondary": "#0f766e",
                "border": "rgba(6, 182, 212, 0.3)",
                "success": "#059669",
                "warning": "#d97706",
                "error": "#dc2626",
                "gradient_start": "#06b6d4",
                "gradient_end": "#0e7490"
            }
        }
        self.current_theme = "default_blue"
        self.init_database()

    def init_database(self):
        """初始化数据库中的主题表"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()

            # 创建主题设置表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS theme_settings (
                    id INTEGER PRIMARY KEY,
                    theme_key TEXT,
                    last_updated DATETIME DEFAULT CURRENT_TIMESTAMP
                )
            ''')

            # 检查是否有已保存的主题
            cursor.execute('SELECT theme_key FROM theme_settings WHERE id = 1')
            result = cursor.fetchone()

            if result and result[0] in self.themes:
                self.current_theme = result[0]
            else:
                # 如果没有保存的主题或主题不存在，插入默认主题
                cursor.execute('''
                    INSERT OR REPLACE INTO theme_settings (id, theme_key) 
                    VALUES (1, ?)
                ''', (self.current_theme,))

            conn.commit()
            conn.close()
            print(f"主题数据库初始化成功，当前主题: {self.themes[self.current_theme]['name']}")
        except Exception as e:
            print(f"主题数据库初始化失败: {e}")

    def get_current_theme(self):
        """获取当前主题"""
        return self.current_theme

    def get_theme_data(self, theme_key=None):
        """获取指定主题的数据"""
        if theme_key is None:
            theme_key = self.current_theme

        if theme_key in self.themes:
            return self.themes[theme_key]
        return self.themes["default_blue"]

    def get_all_themes(self):
        """获取所有可用主题"""
        return self.themes

    def set_theme(self, theme_key):
        """设置当前主题并保存到数据库"""
        if theme_key in self.themes:
            old_theme = self.current_theme
            self.current_theme = theme_key
            try:
                conn = sqlite3.connect(self.db_path)
                cursor = conn.cursor()

                cursor.execute('''
                    INSERT OR REPLACE INTO theme_settings (id, theme_key, last_updated)
                    VALUES (1, ?, CURRENT_TIMESTAMP)
                ''', (theme_key,))

                conn.commit()
                conn.close()
                print(f"主题已切换: {self.themes[old_theme]['name']} -> {self.themes[theme_key]['name']}")
                return True
            except Exception as e:
                print(f"保存主题设置失败: {e}")
                self.current_theme = old_theme  # 回滚
                return False
        return False

    def apply_theme_to_app(self, app):
        """将主题应用到整个应用程序"""
        theme = self.get_theme_data()

        # 创建调色板
        palette = QPalette()

        # 根据主题类型设置调色板
        is_dark_theme = theme["background"] in ["#0f0f23"]  # 检查是否为深色主题

        if is_dark_theme:
            # 深色主题
            palette.setColor(QPalette.ColorRole.Window, QColor(theme["background"]))
            palette.setColor(QPalette.ColorRole.WindowText, QColor(theme["text"]))
            palette.setColor(QPalette.ColorRole.Base, QColor(theme["card_bg"]))
            palette.setColor(QPalette.ColorRole.AlternateBase, QColor(theme["secondary"]))
            palette.setColor(QPalette.ColorRole.Text, QColor(theme["text"]))
            palette.setColor(QPalette.ColorRole.Button, QColor(theme["primary"]))
            palette.setColor(QPalette.ColorRole.ButtonText, QColor("#ffffff"))
            palette.setColor(QPalette.ColorRole.Highlight, QColor(theme["accent"]))
            palette.setColor(QPalette.ColorRole.HighlightedText, QColor("#ffffff"))
        else:
            # 浅色主题
            palette.setColor(QPalette.ColorRole.Window, QColor(theme["background"]))
            palette.setColor(QPalette.ColorRole.WindowText, QColor(theme["text"]))
            palette.setColor(QPalette.ColorRole.Base, QColor("#ffffff"))
            palette.setColor(QPalette.ColorRole.AlternateBase, QColor(theme["background"]))
            palette.setColor(QPalette.ColorRole.Text, QColor(theme["text"]))
            palette.setColor(QPalette.ColorRole.Button, QColor(theme["primary"]))
            palette.setColor(QPalette.ColorRole.ButtonText, QColor("#ffffff"))
            palette.setColor(QPalette.ColorRole.Highlight, QColor(theme["accent"]))
            palette.setColor(QPalette.ColorRole.HighlightedText, QColor("#ffffff"))

        # 应用调色板
        app.setPalette(palette)

        # 设置全局样式表
        app.setStyleSheet(f"""
            QPushButton {{
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 {theme["gradient_start"]}, 
                    stop:1 {theme["gradient_end"]});
                color: white;
                border-radius: 8px;
                padding: 10px 20px;
                font-weight: bold;
                border: none;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            }}
            QPushButton:hover {{
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 {theme["accent"]}, 
                    stop:1 {theme["primary"]});
                box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
                transform: translateY(-1px);
            }}
            QPushButton:pressed {{
                background: {theme["secondary"]};
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
                transform: translateY(0px);
            }}
            QFrame {{
                border-radius: 16px;
            }}
            QScrollBar:vertical {{
                background: {theme["background"]};
                width: 12px;
                border-radius: 6px;
            }}
            QScrollBar::handle:vertical {{
                background: {theme["primary"]};
                border-radius: 6px;
                min-height: 20px;
            }}
            QScrollBar::handle:vertical:hover {{
                background: {theme["accent"]};
            }}
        """)

        return theme
